import datetime
import copy
import numpy as np
import pandas as pd
import Core.Gadget as Gadget
from SystematicFactors.General import *



def Calc_PE_Level(database, datetime1, datetime2):
    datetime0 = datetime.datetime(2005, 4, 1)
    df = WSD_Multi_Fields("000300.SH", datetime0, datetime2, ["pe_ttm"])
    df.dropna(subset=["pe_ttm"], inplace=True)
    df = fill_historical_probability_percentile(df, "pe_ttm", return_raw_data=True)
    df.set_index("index", inplace=True)
    df.index = pd.to_datetime(df.index)
    df["Release_Date"] = df.index
    # df.to_csv("d:/pelevel.csv")

    # print(df)
    #
    df_weekly = df.resample("W").last()
    df_weekly["Dif"] = df_weekly["pe_ttm_Rank"].diff(1)
    df_weekly["Report_Date"] = df_weekly.index
    #
    print(df_weekly)
    #
    df["Report_Date"] = df.index
    Save_Systematic_Factor_To_Database(database, df, save_name='PE_Level_HS300', field_name='pe_ttm_Rank')
    Save_Systematic_Factor_To_Database(database, df_weekly, save_name='PE_Level_HS300_Weekly_Dif', field_name='Dif')


# DVDM10YTRY
def Calc_Dividend_To_TBond_Yield(database, datetime1, datetime2):

    df1 = WSD_Multi_Fields("000300.SH", datetime1, datetime2, ["dividendyield2"])  # 股息率（近12个月）
    # print(df1)
    df2 = EDB('S0059749', datetime1, datetime2)  # 国债到期收益率 10年

    df = pd.merge(df1, df2, how="inner", left_index=True, right_index=True)
    df['Gap'] = df['dividendyield2'] - df['S0059749']
    df["Release_Date"] = df.index
    #
    df_weekly = df.resample("W").last()
    df_weekly["Dif"] = df_weekly["Gap"].diff(1)
    df_weekly["Report_Date"] = df_weekly.index
    #
    # print(df_weekly)
    #
    df["Report_Date"] = df.index
    Save_Systematic_Factor_To_Database(database, df, save_name='HS300_Dividend_To_Tbond_Yield', field_name='Gap')
    Save_Systematic_Factor_To_Database(database, df_weekly, save_name='HS300_Dividend_To_Tbond_Yield_Weekly',
                                       field_name='Gap')
    Save_Systematic_Factor_To_Database(database, df_weekly, save_name='HS300_Dividend_To_Tbond_Yield_Weekly_Dif',
                                       field_name='Dif')


def Calc_EPS_Chg_To_Amt_Chg(database, datetime1, datetime2):

    df = WSD_Multi_Fields("000300.SH", datetime1, datetime2, ["pe_ttm", "amt"])  #
    df.index = pd.to_datetime(df.index)
    df["Release_Date"] = df.index

    df['amt_ma'] = df["amt"].rolling(window=5).mean()
    window = 20
    df['pe_chg'] = df['pe_ttm'] / df['pe_ttm'].shift(window) - 1
    df['amt_chg'] = df['amt_ma'] / df['amt_ma'].shift(window) - 1
    df['chg_ratio'] = df['pe_chg'] / df['amt_chg']
    print(df)
    # df.to_csv("d:/HS300_PE_Chg_To_Amt_Chg_Weekly.csv")
    #
    df_weekly = df.resample("W").last()
    df_weekly["Dif"] = df_weekly["chg_ratio"].diff(1)
    df_weekly["Report_Date"] = df_weekly.index
    #
    print(df_weekly)
    #
    df["Report_Date"] = df.index
    Save_Systematic_Factor_To_Database(database, df, save_name='HS300_PE_Chg_To_Amt_Chg', field_name='chg_ratio')
    Save_Systematic_Factor_To_Database(database, df_weekly, save_name='HS300_PE_Chg_To_Amt_Chg_Weekly', field_name='chg_ratio')
    Save_Systematic_Factor_To_Database(database, df_weekly, save_name='HS300_PE_Chg_To_Amt_Chg_Weekly_Dif', field_name='Dif')


if __name__ == '__main__':
    #
    path_filename = os.getcwd() + "\..\Config\config_local.json"
    database = Config.create_database(database_type="MySQL", config_file=path_filename, config_field="MySQL")

    datetime1 = datetime.datetime(2000, 1, 1)
    datetime2 = datetime.datetime(2023, 3, 31)
    #
    Calculate_Aggregate_ROE(database, datetime1, datetime2)
    #
    w.start()
    datetime1 = datetime.datetime(2000, 1, 1)
    datetime2 = datetime.datetime(2020, 8, 7)
    # Calc_Dividend_To_TBond_Yield(database, datetime1, datetime2)
    # Calc_EPS_Chg_To_Amt_Chg(database, datetime1, datetime2)
    # Calc_PE_Level(database, datetime1, datetime2)